<!DOCTYPE html>



  


<html class="theme-next muse use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Hexo, NexT" />










<meta name="description" content="本文主要梳理Kryo序列化基本实现。重点剖析Kryo#writeClassAndObject、Kryo#readClassAndObject方法。 1、源码分析Kryo#writeClassAndObject12345678910111213141516171819public void writeClassAndObject (Output output, Object object) &amp;#12">
<meta property="og:type" content="article">
<meta property="og:title" content="源码分析Dubbo序列化-源码分析kryo序列化实现原理">
<meta property="og:url" content="https://www.codingw.net/posts/c1c80d83.html">
<meta property="og:site_name" content="中间件兴趣圈">
<meta property="og:description" content="本文主要梳理Kryo序列化基本实现。重点剖析Kryo#writeClassAndObject、Kryo#readClassAndObject方法。 1、源码分析Kryo#writeClassAndObject12345678910111213141516171819public void writeClassAndObject (Output output, Object object) &amp;#12">
<meta property="og:locale">
<meta property="article:published_time" content="2020-11-21T10:55:01.000Z">
<meta property="article:modified_time" content="2021-04-26T12:10:49.663Z">
<meta property="article:author" content="中间件兴趣圈">
<meta property="article:tag" content="中间件">
<meta name="twitter:card" content="summary">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '',
    scheme: 'Muse',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://www.codingw.net/posts/c1c80d83.html"/>





  <title>源码分析Dubbo序列化-源码分析kryo序列化实现原理 | 中间件兴趣圈</title>
  








<meta name="generator" content="Hexo 5.4.0"></head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">中间件兴趣圈</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">微信搜『中间件兴趣圈』，回复『Java』获取200本优质电子书</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            归档
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://www.codingw.net/posts/c1c80d83.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="中间件兴趣圈">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">源码分析Dubbo序列化-源码分析kryo序列化实现原理</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2020-11-21T18:55:01+08:00">
                2020-11-21
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/dubbo/" itemprop="url" rel="index">
                    <span itemprop="name">dubbo</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          
             <span id="/posts/c1c80d83.html" class="leancloud_visitors" data-flag-title="源码分析Dubbo序列化-源码分析kryo序列化实现原理">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv"><i class="fa fa-file-o"></i>
            <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>次
            </span>
          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <div id="vip-container"><p>本文主要梳理Kryo序列化基本实现。重点剖析Kryo#writeClassAndObject、Kryo#readClassAndObject方法。</p>
<h2 id="1、源码分析Kryo-writeClassAndObject"><a href="#1、源码分析Kryo-writeClassAndObject" class="headerlink" title="1、源码分析Kryo#writeClassAndObject"></a>1、源码分析Kryo#writeClassAndObject</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line">public void writeClassAndObject (Output output, Object object) &#123;</span><br><span class="line">	if (output &#x3D;&#x3D; null) throw new IllegalArgumentException(&quot;output cannot be null.&quot;);</span><br><span class="line">	beginObject();                                             &#x2F;&#x2F; @1</span><br><span class="line">	try &#123;</span><br><span class="line">		if (object &#x3D;&#x3D; null) &#123;</span><br><span class="line">			writeClass(output, null);              &#x2F;&#x2F; @2</span><br><span class="line">			return;</span><br><span class="line">		&#125;</span><br><span class="line">		Registration registration &#x3D; writeClass(output, object.getClass());   &#x2F;&#x2F; @3</span><br><span class="line">		if (references &amp;&amp; writeReferenceOrNull(output, object, false)) &#123;    &#x2F;&#x2F; @4</span><br><span class="line">			registration.getSerializer().setGenerics(this, null);</span><br><span class="line">			return;</span><br><span class="line">		&#125;</span><br><span class="line">		if (TRACE || (DEBUG &amp;&amp; depth &#x3D;&#x3D; 1)) log(&quot;Write&quot;, object);</span><br><span class="line">		registration.getSerializer().write(this, output, object);  &#x2F;&#x2F; @5</span><br><span class="line">	&#125; finally &#123;</span><br><span class="line">		if (--depth &#x3D;&#x3D; 0 &amp;&amp; autoReset) reset();       &#x2F;&#x2F; @6</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>代码@1：开始序列化， 将dept自增，表示当前深度，因为在序列化一个对象时，该方法有可能会被递归调用，每递归调用增加1，一次调用结束后在finally字句中自减。</p>
<p>代码@2：如果对象为空，则调用writeClass(DefaultSerializers$ClassSerializer),序列化为空。</p>
<p>代码@3：如果对象不为空，首先序列化对象所属的Class实例，从这里可以看出，Kryo在序列化时，首先先序列化类型。</p>
<p>代码@4：如果references 为true(默认为true，可以序列化循环依赖)，则调用writeReferenceOrNull序列化。</p>
<p>代码@5：如果references 为false，则调用write序列化，此时如果对象存在循环依赖，则会抛出 throw new KryoException(“Max depth exceeded: “ + depth)异常,如果object为基本类型，也将通过该方法完成值的序列化。</p>
<p>代码@6：完成序列化后，恢复相关数据。也就是说Kryo实例并不是线程安全的。<br>默认references 为true，表示支持循环嵌套，我们接下来重点跟踪一下writeReferenceOrNull方法。</p>
<h3 id="1-1-源码分析writeReferenceOrNull方法"><a href="#1-1-源码分析writeReferenceOrNull方法" class="headerlink" title="1.1 源码分析writeReferenceOrNull方法"></a>1.1 源码分析writeReferenceOrNull方法</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line">&#x2F;** @param object May be null if mayBeNull is true.</span><br><span class="line">	 * @return true if no bytes need to be written for the object. *&#x2F;</span><br><span class="line">	boolean writeReferenceOrNull (Output output, Object object, boolean mayBeNull) &#123;     &#x2F;&#x2F; @1</span><br><span class="line">		if (object &#x3D;&#x3D; null) &#123;                                                                                                    &#x2F;&#x2F; @2                    </span><br><span class="line">			if (TRACE || (DEBUG &amp;&amp; depth &#x3D;&#x3D; 1)) log(&quot;Write&quot;, null);</span><br><span class="line">			output.writeVarInt(Kryo.NULL, true);</span><br><span class="line">			return true;</span><br><span class="line">		&#125;</span><br><span class="line">		if (!referenceResolver.useReferences(object.getClass())) &#123;                                  &#x2F;&#x2F; @3</span><br><span class="line">			if (mayBeNull) output.writeVarInt(Kryo.NOT_NULL, true);</span><br><span class="line">			return false;</span><br><span class="line">		&#125;</span><br><span class="line"></span><br><span class="line">		&#x2F;&#x2F; Determine if this object has already been seen in this object graph.</span><br><span class="line">		int id &#x3D; referenceResolver.getWrittenId(object);                                                 &#x2F;&#x2F; @4</span><br><span class="line"></span><br><span class="line">		&#x2F;&#x2F; If not the first time encountered, only write reference ID.</span><br><span class="line">		if (id !&#x3D; -1) &#123;                                                                                                        &#x2F;&#x2F; @5</span><br><span class="line">			if (DEBUG) debug(&quot;kryo&quot;, &quot;Write object reference &quot; + id + &quot;: &quot; + string(object));</span><br><span class="line">			output.writeVarInt(id + 2, true); &#x2F;&#x2F; + 2 because 0 and 1 are used for NULL and NOT_NULL.</span><br><span class="line">			return true;</span><br><span class="line">		&#125;</span><br><span class="line"></span><br><span class="line">		&#x2F;&#x2F; Otherwise write NOT_NULL and then the object bytes.</span><br><span class="line">		id &#x3D; referenceResolver.addWrittenObject(object);     &#x2F;&#x2F; @6</span><br><span class="line">		output.writeVarInt(NOT_NULL, true);</span><br><span class="line">		if (TRACE) trace(&quot;kryo&quot;, &quot;Write initial object reference &quot; + id + &quot;: &quot; + string(object));</span><br><span class="line">		return false;                                                              &#x2F;&#x2F; @7</span><br><span class="line">	&#125;</span><br></pre></td></tr></table></figure>
<p>代码@1：参数说明：Output output：输出流；Object object：待序列化的对象；</p>
<p>代码@2：如果对象为空，写入Kryo.NULL(0)，然后返回true，表示需要设置generic，后续会讲解一下generic(泛型支持)。</p>
<p>代码@3：如果是基本类型，如果maybe(值可能为空)，但该方法不为空，则设置为Kryo.NOT_NULL,然后返回false，表示非引用类型，需要持久化值。</p>
<p>代码@4：判断该对象是否在对象图中已被序列化一次。（其实现方式ListReferenceResolver、MapReferenceResolver）。</p>
<p>ListReferenceResolver#getWrittenId </p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">public int getWrittenId (Object object) &#123;</span><br><span class="line">	for (int i &#x3D; 0, n &#x3D; seenObjects.size(); i &lt; n; i++) &#123;</span><br><span class="line">		if (seenObjects.get(i) &#x3D;&#x3D; object) &#123;</span><br><span class="line">			return i;</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">	return -1;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>代码@5：如果writtenId不等于-1，表示该对象已被序列化，直接序列化ID，直接返回true,然后结束writeClassAndObject该方法，表示该对象实例完成。</p>
<p>代码@6：为object构建一个ID，这个ID数据是在一次嵌套调用writeClassAndObject内有效，然后writeClassAndObject结束后，会调用reset方法，将其清空，然后先写入为空标识，并返回false，也就是第一次序列化对象时，返回false，会进入到writeClassAndObject的代码@5中。<br>Kryo#writeClassAndObject 代码@5</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">registration.getSerializer().write(this, output, object);  &#x2F;&#x2F; @5</span><br></pre></td></tr></table></figure>
<p>其实其重点关键，还是writeClassAndObject#writeClass也就是上文说的代码@3，在序列化对象之前，首先先序列化该对象的类型，然后需要返回对应的字段序列器。例如，如果类的类型为java.util.Map，则首先先要记录类型为Map，然后返回可以序列化Map的序列器，再例如类型如果是java.lang.String，则先序列化类型，然后序列化值，序列化值的序列器则为DefaultSerializers\$StringSerializer，那如果是一个对象类型，例如cn.uce.demo.Student，自然，第一步是先序列化类型cn.uce.demo.Student，接下来就需要序列化Student的各个字段的信息，返回的序列化为DefaultSerializers$FieldSerializer,然后可以通过FieldSeriaizer返回Student的属性列表，然后单独一个字段一个字段的序列化，其顺序也就是，先类型，再序列化值。这样就递归完成了一个对象的序列化操作。</p>
<span id="more"></span>

<p><strong>Kryo序列化实现原理</strong> ：<br>1、先序列化类型(Class实例)，然后根据类型返回相应的序列化器(上一篇详细介绍了各种类型的序列化器)。</p>
<p>2、再序列化该类型的值。</p>
<p>3、如果自定义类型，例如(cn.uce.demo.Student)，则返回的值序列化器为DefaultSerializers$FieldSerializer,然后一个字段一个字段的序列化，当然其序列化类型也是，先类型再值的模式，递归进行，最终完成。</p>
<p>4、引入了对象图的概念来消除循环依懒的序列化，已序列化的对象，在循环引用时，只是用一个int类型来表示该对象值，类似一种缓存的概念。</p>
<p><strong>Kryo与java 序列化的区别</strong><br>kryo的设计目的是指对象值的序列化，关注的是数据有效数据的传输，减少需要序列化的元数据信息。</p>
<p>这一点通过Kryo对Class对象的序列化，也就是类型的序列化就能看出端倪。Kryo对Class的序列化只需要化Class的全路径名，在反序列化时根据Class通过类加载进行加载，大大减少了序列化后的文件大小，能极大提高性能。</p>
<p>Kryo的核心设计理念就是尽最大可能减少序列化后的文件大小，其举措1就是通过对long,int等数据类型，采用变长字节存储来代替java中使用固定字节(4,8)字节的模式，因为在软件开发中，对象的这些值基本上都是小值，能节省很多空间，第二个举措是使用了类似缓存的机制，在一次序列化对象中，在整个递归序列化期间，相同的对象，只会序列化一次，后续的用一个局部int值来代替。</p>
</div>

			<script src="https://my.openwrite.cn/js/readmore.js" type="text/javascript"></script>
			<script>
			var isMobile = navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i);
			if (!isMobile) {
			    var btw = new BTWPlugin();
			    btw.init({
			        "id": "vip-container",
			        "blogId": "18019-1573088808868-542",
			        "name": "中间件兴趣圈",
			        "qrcode": "https://img-blog.csdnimg.cn/20190314214003962.jpg",
			        "keyword": "more"
			    });
			}
			</script>
		
      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/posts/aeb9a46c.html" rel="next" title="Canal binlog 日志 Dump 流程分析">
                <i class="fa fa-chevron-left"></i> Canal binlog 日志 Dump 流程分析
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/posts/caabd6c1.html" rel="prev" title="源码分析Dubbo序列化-源码分析kryo各数据类型的序列化编码机制">
                源码分析Dubbo序列化-源码分析kryo各数据类型的序列化编码机制 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name"></p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">139</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">18</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#1%E3%80%81%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90Kryo-writeClassAndObject"><span class="nav-number">1.</span> <span class="nav-text">1、源码分析Kryo#writeClassAndObject</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-1-%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90writeReferenceOrNull%E6%96%B9%E6%B3%95"><span class="nav-number">1.1.</span> <span class="nav-text">1.1 源码分析writeReferenceOrNull方法</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">中间件兴趣圈</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Muse</a> v5.1.4</div>




        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      <i class="fa fa-user"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      
    </span>
  

  
    <span class="site-pv">
      <i class="fa fa-eye"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      
    </span>
  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("NNEhOL0iOcflg8f1U3HUqiCq-gzGzoHsz", "7kSmkbbb3DktmHALlShDsBUF");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  

  
  

  

  

  

</body>
</html>
